<?php
error_reporting(E_ALL);

/**
 * Context Class.
 * Singleton resource for
 * session and site information.
 *
 */

class Context
{
    protected $_user;

	function __construct() 
    {
        global $db ;

        require_once "Db.class.php";
        if( ! isset( $db ) ) {
            die("Fatal database error.");
        }

        session_start();

        require_once "User.class.php";
        if($this->IsLoggedIn()) {
            $this->_user = new User($this->SessionUserID());
            $this->LogEvent( "cxContext", null, "was logged in");
        }
        else {
            $this->_user = new User();
            $this->LogEvent( "cxContext", null, "not logged in");
        }
	}

    function __destruct()
    {
        global $db;

        $this->LogEvent("dxContext");
        unset($db);
        session_write_close();
    }

    public function Dump()
    {
        var_dump($this);
    }

    public function User()
    {
        return $this->_user;
    }

    public function UserName()
    {
        return $this->User()->FullName();
    }

    public function UserEmail()
    {
        return $this->User()->Email();
    }

    public function IsUserPending() {
        return $this->User()->IsPending();
    }

    public function UserID() {
        return $this->SessionUserID();
    }

    public function SetUserName($name) {
        $this->User()->SetName($name);
    }

    public function UserStatus() {
        return $this->User()->Status();
    }

    public function StatusCounts() {
        global $db;
        $sql = "SELECT status, COUNT(1) AS scount
                FROM users
                GROUP BY status";
        return $db->SqlRows($sql);
    }

    public function DenyUser($ary) {
        global $db;
        $id = $ary["id"];
        $sql = "UPDATE users
                SET status = 'D'
                WHERE id = $id";
        $db->SqlExecute($sql);
        $this->LogEvent("DENY", $id);
    }

    public function ApproveUser($ary) {
        global $db;
        $this->UpdateUser($ary);
        $id = $ary["id"];
        $sql = "UPDATE users
                SET status = 'A'
                WHERE id = $id";
        $db->SqlExecute($sql);
        $this->LogEvent("APPROVE", $id);
    }

    public function HoldUser($id) {
        global $db;
        $this->UpdateUser($ary);
        $id = $ary["id"];
        $sql = "UPDATE users
                SET status = 'H'
                WHERE id = $id";
        $db->SqlExecute($sql);
        $this->LogEvent("HOLD", $id);
    }

    public function AddUser($ary) {
        global $db;

        $sql = "SELECT 1 FROM users
                WHERE email = '{$ary['email']}'";

        $is = $db->SqlExists($sql);
        if($is) {
            die("User email already exists");
        }
    
        $sql = "INSERT INTO users
                (
                    first_name,
                    last_name,
                    email,
                    residence_status,
                    street_address,
                    mailing_address,
                    city_state_zip,
                    phone,
                    business_name,
                    business_address,
                    business_phone,
                    is_business_owner,
                    comment,
                    MD5_password
                )
                VALUES
                (
                    ".QuoteOrNull($ary['first_name']).",
                    ".QuoteOrNull($ary['last_name']).",
                    ".QuoteOrNull($ary['email']).",
                    ".QuoteOrNull($ary['res_status']).",
                    ".QuoteOrNull($ary['street_address']).",
                    ".QuoteOrNull($ary['mailing_address']).",
                    ".QuoteOrNull($ary['city_state_zip']).",
                    ".QuoteOrNull($ary['phone']).",
                    ".QuoteOrNull($ary['business_name']).",
                    ".QuoteOrNull($ary['business_address']).",
                    ".QuoteOrNull($ary['business_phone']).",
                    ".NumericNull($ary['is_business_owner']).",
                    ".QuoteOrNull($ary['comment']).",
                    ".QuoteOrNull($ary['password'])."
                )";
        $n = $db->SqlExecute($sql);
        if($n > 0) {
            $sql = "SELECT id FROM users
                    WHERE email = '{$ary['email']}'";
            $id = $db->SqlOneValue($sql);
            $this->LogEvent("ADDUSER", null, "id ".$id);
            $this->set_session_user_id($id);
        }
    }

    public function UpdateUser($ary) {
        global $db;
        $sql = "UPDATE users
                SET 
                    first_name =
                    ".QuoteOrNull($ary['first_name']).",
                    last_name =
                    ".QuoteOrNull($ary['last_name']).",
                    email =
                    ".QuoteOrNull($ary['email']).",
                    residence_status =
                    ".QuoteOrNull($ary['res_status']).",
                    street_address =
                    ".QuoteOrNull($ary['street_address']).",
                    mailing_address =
                    ".QuoteOrNull($ary['mailing_address']).",
                    city_state_zip =
                    ".QuoteOrNull($ary['city_state_zip']).",
                    phone =
                    ".QuoteOrNull($ary['phone']).",
                    business_name =
                    ".QuoteOrNull($ary['business_name']).",
                    business_address =
                    ".QuoteOrNull($ary['business_address']).",
                    business_phone =
                    ".QuoteOrNull($ary['business_phone']).",
                    is_business_owner =
                    ".NumericNull($ary['is_business_owner']).",
                    comment =
                    ".QuoteOrNull($ary['comment']).",
                    admin_comment =
                    ".QuoteOrNull($ary['admin_comment'])."
                WHERE id = {$ary['id']}";
        $db->SqlExecute($sql);
        $this->LogEvent("UPDATE");
    }

    public function EmailExists($email) {
        global $db;
        if(empty($email)) {
            return false;
        }
        $sql = "SELECT 1 FROM users
                WHERE email = '{$email}'";
        return $db->SqlExists($sql);
    }

    public function IsValidEmailPasswordMD5($eml, $pwd) {
        return ($this->EmailPasswordToID($eml, $pwd) > 0);
    }

    public function TryLogin($eml, $pwd)
    {
        global $db;
        $md5pwd = md5($pwd);
        $sql = "SELECT id FROM users
                WHERE email = '{$eml}'
                    AND md5_password = '{$md5pwd}'";
        $id = $db->SqlOneValue($sql);
        if(empty($id)) {
            return false;
        }
        require_once "User.class.php";
        $this->_user = new User($id);
        $this->set_session_user_id($id);
    }

/*
    private function LoginForID($id)
    {
        require_once "User.class.php";
        $this->_user = new User($id);
        $this->set_session_user_id($id);
    }
*/

    private function set_session_user_id($id)
    {
        $_SESSION['userid'] = $id;
    }

    private function clear_session_user_id()
    {
        unset($_SESSION['userid']);
    }

    public function SessionUserID()
    {
        return empty($_SESSION['userid'])
            ? 0
            : $_SESSION['userid'];
    }

    public function IsReallyLoggedIn() {
        global $db;
        if(!$this->IsLoggedIn()) {
            return false;
        }
        $id = $this->SessionUserID();
        $sql = "SELECT 1 FROM users 
                WHERE id = {$id}";
        return $db->SqlExists($sql);
    }

    public function IsLoggedIn() {
        return !empty($_SESSION['userid']);
    }

    public function Logout()
    {
        if($this->IsLoggedIn()) {
            $this->clear_session_user_id();
        }
    }

    public function PageName() {
        global $post;
        return $post->post_name;
    }

    public function PageUrl() {
        return $this->UrlSelf();
    }

    public function PageContent() {
        global $post;
        return $post->post_content;
    }

    public function ThisUrl() {
        return UrlSelf();
    }
    
	public function LogEvent($eventcode,
                             $userid = null,
                             $data = null) {
		global $db;

        if(!$db) return;
        $sessionid  = session_id();
        if(empty($userid)) {
            $userid = $this->SessionUserID();
        }
        $eventcode  = QuoteOrNull($eventcode) ;
        $data       = QuoteOrNull($data) ;
        $userid     = NumericNull($userid) ;

		$sql = "INSERT INTO pagelog
                (
                    sid,
                    eventtime,
                    uid,
                    eventcode,
                    data
                ) VALUES (
                    '$sessionid',
                    NOW(),
                    $userid,
                    $eventcode,
                    $data
                )";
		$db->SqlExecute($sql);
	}

    public function AddTask($taskcode, $inserted_by, $data) {
        global $db;
        $taskcode    = QuoteOrNull($taskcode);
        $inserted_by = QuoteOrNull($inserted_by);
        $data        = QuoteOrNull($data);
        $sql = "INSERT INTO tasks (task_code, inserted_by, inserted_time, data)
                VALUES ($taskcode, $inserted_by, NOW(), $data)";
        $db->SqlExecute($sql);
    }

    public function SetActivationKey($usr, $key) {
        global $db;
        $sql = "UPDATE users
                SET activationkey = '$key',
                    activationtime = NOW()
                WHERE
                    email = '$usr'";
        $db->SqlExecute($sql);
    }

    public function RandomMD5() {
        global $db;
        $sql = "SELECT MD5(RAND())";
        return $db->SqlOneValue($sql);
    }

    public function SendResetEmail($usr) {
        $key = $this->RandomMD5();
        $this->SetActivationKey($usr, $key);
        $this->send_reset_email($usr, $key);
    }

    public function ResetKeyToEmail($key) {
        global $db;
        $sql = "SELECT email FROM users
                WHERE activationkey = '$key'";
        return $db->SqlOneValue($sql);
    }

    public function ResetUserPassword($email, $pwMD5) {
        global $db;
        $sql = "UPDATE users
                SET md5_password = '$pwMD5'
                WHERE email = '$email'";
        $db->SqlExecute($sql);
    }

    private function send_reset_email($email, $key) {
        $to         = $email;
        $subject    = "OneBainbridge Password Reset";
        $link       = "www.tbicl.org/registration?resetkey=".$key;
        $message    = 
            "<p>This is in response to your request for login password reset 
            at www.OneBainbridge.org. 
            To reset your password, please visit this link
            (or copy and paste this link in your browser window).</p>
            <p>Thank You</p>

            <p>{$link}</p>\n";

            wp_mail($to, $subject, $message);
    }
}
?>
